import { createRouter, createWebHistory } from 'vue-router'
import { useUserInfoStore } from '@/stores/userInfo'
import { getToken, removeToken } from '@/untils/token-untils'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      // 重定向   项目启动之后   会自动打开下面这个页面
      redirect: 'headlineNews',
    },
    {
      path: '/headlineNews',
      name: 'HeadlineNews',
      component: () => import('@/pages/HeadlineNews/index.vue'),
    },
    {
      path:'/login',
      name:'Login',
      component: () => import('@/pages/Login/index.vue'),
    },
    {
      path:'/register',
      name:'Register',
      component: () => import('@/pages/Register/index.vue'),
    },
    {
      path:'/detail',
      name:'Detail',
      component: () => import('@/pages/Detail/index.vue'),
    },
    {
      path:'/addormodifynews',
      name:'AddOrModifyNews',
      component: () => import('@/pages/AddOrModifyNews/index.vue'),
    },
    {
      path:'/eLogin',
      name:'eLogin',
      component: () => import('@/pages/Login/eLogin.vue'),
    },
    // 我添加的代码
    {
      path:'/eLogin',
      name:'eLogin',
      component: () => import('@/pages/Login/eLogin.vue'),
    }
  ],
})

  /* userInfoStore.$subscribe((mutation, state) => {
    console.log('userInfoStore updated:', state)
  }) */

//全局的前置守卫
router.beforeEach( async (to, form, next) => {
  const userInfoStore = useUserInfoStore()
  const token = getToken()

  //console.log("router.beforeEach uid=" + userInfoStore.uid)
  //console.log("router.beforeEach nickName=" + userInfoStore.nickName)
  
  const userInfo = !!userInfoStore.nickName
  if(token){
    //已经登录过，在进入登录页面，直接跳转到主页
    if(to.path == '/login'){
      next({path: "/"})
    }else{
      if(userInfo){
        //任何页面都能进
        next()
      }else{
        try{
          //没有nickName,第一次登录
          await userInfoStore.getInfo()
          next()
        }catch(error){
          //自带的token可以能有问题，我删除
          removeToken()
        }
      }
    }
  }else{
    //没有token,这是没有登录，直接放行
    next()
  }
})


//全局的后置守卫

export default router
